use std::fs;
use std::path::Path;
use anyhow::Error;

use serde_json::Value;

use crate::error::Res;

pub fn create_polygons<P: AsRef<Path>>(path: P, texture_id: &str) -> Res<()> {
    let buf = fs::read(path)?;
    let image_infos: Value = serde_json::from_slice(&buf)?;
    let items = image_infos.as_array().ok_or(Error::msg("Invalid rectangles json file"))?;
    for item in items {
        let name = &item["name"].as_str().to_owned().unwrap_or("");
        println!(r#"[node name="{name}" type="Polygon2D" parent="."]"#);
        println!(r#"texture = ExtResource("{texture_id}")"#);
        let rect = &item["rect"];
        let x = rect[0].as_i64().unwrap_or(0);
        let y = rect[1].as_i64().unwrap_or(0);
        let w = rect[2].as_i64().unwrap_or(0);
        let h = rect[3].as_i64().unwrap_or(0);
        let vector = format!(r#"({},{},{},{},{},{},{},{})"#,
                             x, y, x + w, y, x + w, y + h, x, y + h);
        println!(r#"polygon = PackedVector2Array{vector}"#);
        println!(r#"uv = PackedVector2Array{vector}"#);
        println!()
    }

    Ok(())
}
